using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;

/// <summary>
/// 负责颜色转换以及后续升采样处理的Pass
/// </summary>
public class SrgbColorConverPass : ScriptableRenderPass
{
    private static readonly ProfilingSampler m_ProfilingSampler = new ProfilingSampler("SrgbColorConvertPass");

    
    RTHandle m_Source;
    RTHandle m_Destination;
    private Material m_blitMat;

    public SrgbColorConverPass()
    {
        this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing;
        SetUp();
    }

    private void SetUp()
    {
        m_blitMat = CoreUtils.CreateEngineMaterial("Hidden/Universal/CoreBlit");
        m_blitMat.EnableKeyword(ShaderKeywordStrings.LinearToSRGBConversion);
    }
    
    
    /// <summary>
    /// 贴图swarp
    /// </summary>
    /// <param name="r"></param>
    /// <param name="cmd"></param>
    void Swap(ref ScriptableRenderer r,CommandBuffer cmd)
    {
        r.SwapColorBuffer(cmd);
        m_Source = r.cameraColorTargetHandle;
        //we want the last blit to be to MSAA
        //if (amountOfPassesRemaining == 0 && !m_HasFinalPass)
        r.EnableSwapBufferMSAA(true);
        m_Destination = r.GetCameraColorFrontBuffer(cmd);
    }
        
    
    public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
    {
        var cmd = renderingData.commandBuffer;
        using (new ProfilingScope(cmd, m_ProfilingSampler))
        {

            var colorLoadAction = RenderBufferLoadAction.DontCare;
            if (m_Destination == k_CameraTarget && !renderingData.cameraData.isDefaultViewport)
                colorLoadAction = RenderBufferLoadAction.Load;
        
            var renderer = renderingData.cameraData.renderer;
            m_Source = renderer.cameraColorTargetHandle;
            m_Destination = renderer.GetCameraColorFrontBuffer(cmd);
        
            Blitter.BlitCameraTexture(cmd, m_Source, m_Destination,colorLoadAction , RenderBufferStoreAction.Store,m_blitMat, 0);
        
            renderer.ConfigureCameraColorTarget(m_Destination);
            Swap(ref renderer,cmd);
        }

    }

    public void Dispose()
    {
        CoreUtils.Destroy(m_blitMat);
    }
}